package cn.wolfcode.luowowo.website.interceptor;


import cn.wolfcode.luowowo.website.annotion.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查
 *extends HandlerInterceptorAdapter 适配器模式
 * implements HandlerInterceptor
 */
public class CheckLoginInterceptor implements HandlerInterceptor{

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    /**
     * 登录检查
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
//        //1. 获取token
//        String token = CookieUtil.getToken(request, response);
//        //2. 通过token查redis进而查询用户对象
//        UserInfo user = userInfoRedisService.getUserByToken(token);
//        //3. 判断用户对象是否存在，如果不存在，直接登录页面
//        if(user == null){
//            response.sendRedirect("/login.html");
//            return false;
//        }
//        return true;

        String token = CookieUtil.getToken(request, response);
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //1. 获取当前请求方法对象 HandlerMethod 动态请求
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //2. 判断其是否贴了@RequireLogin注解
            if(handlerMethod.hasMethodAnnotation(RequireLogin.class)){
                //3. 贴了登录检查
                if(user == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        //4. 没贴 放行 共享用户数据
        request.getSession().setAttribute("userInfo",user);
        return true;
    }
}
